<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href="/">用户管理</a>
      </el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card v-loading="loading">
      <!-- 搜索与添加区域 -->
      <!-- 行 -->
      <el-row :gutter="20">
        <!-- 列 -->
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="UserList">
            <el-button slot="append" icon="el-icon-search" @click="queryUserInfo"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.state" @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180px">
          <!-- 作用域插槽 -->
          <!-- slot-scope="scope" -->
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row._id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row._id)"></el-button>
            <!-- 文字提示组件 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <!-- 分配角色按钮 -->
              <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户信息" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
        <el-form-item label="用户名：" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="电话：" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="角色：" prop="role_name">
          <!-- <el-input v-model="addForm.role_name"></el-input> -->
          <el-select
            v-model="addForm.role_scope"
            placeholder="请选择角色"
            :change="selectRole(addForm.role_scope)"
          >
            <el-option
              v-for="item in selectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户信息对话框 -->
    <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
        <el-form-item label="用户名:" >
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="手机号:" prop="mobile">
          <el-input v-model="editForm.mobile" ></el-input>
        </el-form-item>
        <el-form-item label="角色:"  prop="role_name">
          <el-select
            v-model="editForm.role_name"
            placeholder="请选择角色"
            :change="editSelectRole(editForm.role_name)"
          >
            <el-option
              v-for="item in selectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUserList,
  updateUserInfo,
  queryUser,
  addNewUser,
  queryIdUser,
  delIdUser
} from '../../api/user/user.js'
export default {
  data() {
    // 手机号验证
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }

    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        // 当前的页数
        pageNum: 1,
        // 当前每页显示多少条
        pageSize: 5
      },
      userList: [],
      total: 0,
      loading: false,
      //   控制添加用户的对话框显示与隐藏
      addDialogVisible: false,
      //   添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        mobile: '',
        role_name: '',
        role_scope: ''
      },
      //   添加表单的规则对象
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输手机号码', trigger: 'blur' },
          { min: 11, max: 11, message: '长度在 11 个字符', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
        role_name: [{ required: true, message: '选择角色', trigger: 'blur' }]
      },
      //   添加用户的角色选择器可选数据
      selectOptions: [
        {
          value: '3',
          label: '管理员'
        },
        {
          value: '2',
          label: '经理'
        },
        {
          value: '1',
          label: '店长'
        },
        {
          value: '0',
          label: '普通用户'
        }
      ],
      //   控制修改用户的对话框显示与隐藏
      editDialogVisible: false,
      // 按id查询到的用户信息给修改用户功能调用
      editForm: {},
      //   修改用户信息验证规则对象
      editFormRules: {
        mobile: [
          { required: true, message: '请输手机号码', trigger: 'blur' },
          { min: 11, max: 11, message: '长度在 11 个字符', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
        role_name: [{ required: true, message: '选择角色', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.UserList()
  },
  methods: {
    // 获取用户列表
    UserList() {
      this.loading = true
      //   console.log(this.queryInfo)
      getUserList(this.queryInfo).then(res => {
        // console.log(res.data)
        if (!res.errcode === 0) return this.$message.error('获取用户列表失败')
        this.userList = res.data.data
        this.total = res.data.Total
        // console.log('total' + this.total)
        this.loading = false
      })
    },
    // 监听 pageSize 改变事件
    handleSizeChange(newSize) {
      //   console.log(newSize)
      this.queryInfo.pageSize = newSize
      this.UserList()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      //   console.log(newPage)
      this.queryInfo.pageNum = newPage
      //   console.log(this.queryInfo.pageNum)
      this.UserList()
    },
    // 监听 用户状态开关
    userStateChange(userIfon) {
      //   console.log(userIfon)

      this.loading = true
      updateUserInfo(userIfon).then(res => {
        // console.log(res.data.errcode)
        if (res.data.errcode !== 0) return this.$message.error('更新用户状态失败')
        this.$message.success('更新用户状态成功')
        this.loading = false
      })
    },
    // 监听查询按钮查询用户信息
    queryUserInfo() {
      //   console.log('查询用户信息' + this.queryInfo)
      this.loading = true
      if (this.queryInfo.query === '') {
        this.UserList()
      } else {
        queryUser(this.queryInfo).then(res => {
          console.log(res)
          this.userList = res.data.data
          this.loading = false
        })
      }
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户按钮
    addUser() {
      this.$refs.addFormRef.validate(valid => {
        console.log(valid)
        console.log(this.addForm)
        if (!valid) return
        // 关闭添加用户对话窗口
        this.addDialogVisible = false
        // 添加表单的请求
        this.loading = true
        addNewUser(this.addForm).then(res => {
          //   console.log(res.data.id)
          this.loading = false
          if (!res.data.id) return this.$message.error('添加新用户失败')
          this.$message.success('添加新用户成功')
          // 重新获取用户列表
          this.UserList()
        })
      })
    },
    // 用户角色选择器，选择后对表单里的角色与权限赋值
    selectRole(id) {
      //   console.log(id)
      if (id === -1) return
      for (let i = 0; i < this.selectOptions.length; i++) {
        if (this.selectOptions[i].value === id) {
          //   console.log(this.selectOptions[i].value + ':' + this.selectOptions[i].label)
          this.addForm.role_name = this.selectOptions[i].label
        }
      }
    },
    // 展示修改用户信息对话框按钮
    showEditDialog(id) {
      //   console.log(id)
      this.loading = true
      queryIdUser(id).then(res => {
        // console.log(res.data)
        this.loading = false
        if (res.data.length === 0) return this.$message.error('查询用户失败')
        this.editForm = res.data.data
        console.log(this.editForm)
        this.editDialogVisible = true
      })
    },
    // 修改用户信息，角色选择器，选择后对表单里的角色与权限赋值
    editSelectRole (id) {
    //   console.log(id)
      if (id === -1) return
      for (let i = 0; i < this.selectOptions.length; i++) {
        if (this.selectOptions[i].value === id) {
          //   console.log(this.selectOptions[i].value + ':' + this.selectOptions[i].label)
          this.editForm.role_name = this.selectOptions[i].label
          this.editForm.scope = this.selectOptions[i].value
        }
      }
      console.log(this.editForm)
    },
    // 监听修改用户对话框的关闭事件
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 修改用户信息按钮提交
    editUserInfo () {
      this.$refs.editFormRef.validate(valid => {
        console.log(valid)
        if (!valid) return
        // 关闭添加用户对话窗口
        this.editDialogVisible = false
        // 添加表单的请求
        this.loading = true
        updateUserInfo(this.editForm).then(res => {
          // console.log(res.data.errcode)
          if (res.data.errcode !== 0) return this.$message.error('更新用户信息失败')
          this.loading = false
          // 重新获取用户列表
          this.UserList()
          this.$message.success('更新用户信息成功')
        })
      })
    },
    // 根据ID删除用户信息按钮
    removeUserById (id) {
      console.log(id)
      this.$confirm('此操作将永久删除该用户, 是否继续?', '删除用户提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res => {
        console.log(res)
        if (res !== 'confirm') return
        console.log('kssc')
        this.loading = true
        delIdUser(id).then(res => {
          console.log(res.data)
          this.loading = false
          if (res.data.deleted === 0) return this.$message.error('删除用户失败')
          // 重新获取用户列表
          this.UserList()
          this.$message.success('删除指定的用户完成')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }

}
</script>

<style lang="less" scoped>
</style>
